package com.tanhua.manage.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.interceptor.AdminHolder;
import com.tanhua.manage.service.AdminService;
import com.tanhua.manage.vo.AdminVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class AdminController {

    @Autowired
    private AdminService adminService;


    /**
     * 接口名称：用户登录验证码图片
     * 接口路径：GET/system/users/verification
     */
    @GetMapping("/verification")
    public  void  verification(String uuid, HttpServletResponse response) throws IOException {
        // 1、设置响应头
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // 响应数据格式
        response.setContentType("image/jpeg");

        //2. 生成一个验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(143, 41);
        // 3. 把验证码保存到redis
        String code = circleCaptcha.getCode();
        adminService.saveCap(uuid, code);
        //4. 把验证码输出到浏览器上即可
        circleCaptcha.write(response.getOutputStream());
    }

    /**
     * 接口名称：用户登录
     *接口路径：POST/system/users/login
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map<String,String> paramMap){
        return adminService.login(paramMap);
    }


    /**
     *接口名称：用户基本信息
     * 接口路径：POST/system/users/profile
     */
    @PostMapping("/profile")
    public ResponseEntity profile(){
        //1. 获取当前登陆的用户
        Admin admin = AdminHolder.get();
        AdminVo adminVo = new AdminVo();
        BeanUtils.copyProperties(admin,adminVo);
        return ResponseEntity.ok(adminVo);
    }


    /**
     *接口名称：用户登出
     * 接口路径：POST/system/users/logout
     */
    @PostMapping("/logout")
    public ResponseEntity logout(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer ", "");
        return adminService.logout(token);
    }
}
